package com.alpha.gateway.utils;

import com.alpha.core.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.net.InetSocketAddress;

/**
 * ServerHttpRequest 辅助类
 *
 * @author chenruwan
 * @since 2022-01-01
 */
public class RequestUtil {
    private RequestUtil() {
    }

    private static final String X_REAL_IP = "X-Real-IP";

    private static final String X_FORWARDED_FOR = "X-Forwarded-For";

    private static final String X_FORWARDED_FOR_SPLIT_SYMBOL = StringUtil.COMMA;

    public static String getRemoteIp(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();

        String forwardedFor = headers.getFirst(X_FORWARDED_FOR);
        if (!StringUtils.isBlank(forwardedFor)) {
            return forwardedFor.split(X_FORWARDED_FOR_SPLIT_SYMBOL)[0].trim();
        }

        String nginxHeader = headers.getFirst(X_REAL_IP);
        if (!StringUtils.isBlank(nginxHeader)) {
            return nginxHeader;
        }

        InetSocketAddress remoteAddress = request.getRemoteAddress();
        if (remoteAddress != null) {
            return remoteAddress.getAddress().getHostAddress();
        }
        return null;
    }
}
